package com.zou.szt.Utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.zou.szt.Constants;

import java.util.Arrays;
import java.util.List;

/**
 * 读取Sp中记录的卡号信息
 * Created by zou on 2016/5/19.
 */
public class GetCards {
    public static String[] getCards(Context context) {
        String cardString = (String) SharedPreferencesUtils.getParam(context, Constants.CARDS, "");
        Log.e("wocao", "getCards: " + SharedPreferencesUtils.getParam(context, Constants.CARDS, ""));

        if (TextUtils.isEmpty(cardString)) {
            return null;
        }

        String[] cards = cardString.split(",");
        return cards;
    }

    public static List<String> getData(Context context) {
        String[] cards = getCards(context);
        if (cards == null) {
            return null;
        } else {
            return Arrays.asList(cards);
        }
    }

    public static boolean requestCards(Context context, String cardNumber) {
        String cardString = (String) SharedPreferencesUtils.getParam(context, Constants.CARDS, "");
        assert cardString != null;
        if (cardString.contains(cardNumber)) {
            SharedPreferencesUtils.setParam(context, Constants.CARDS, cardNumber);
            return true;
        } else {
            return false;
        }

    }


    public static boolean putCards(Context context, String cardNumber) {
        String cardString = (String) SharedPreferencesUtils.getParam(context, Constants.CARDS, "");
        if (TextUtils.isEmpty(cardString)) {
            SharedPreferencesUtils.setParam(context, Constants.CARDS, cardNumber);
            return true;
        } else if (cardString.contains(cardNumber)) {
            return false;
        } else {
            SharedPreferencesUtils.setParam(context, Constants.CARDS, cardString + "," + cardNumber);
            return true;
        }

    }

    public static void removeCards(Context context, String cardNumber) {
        String cardString = (String) SharedPreferencesUtils.getParam(context, Constants.CARDS, "");
        if (cardString.startsWith(cardNumber)) {
            if (TextUtils.equals(cardString, cardNumber)) {
                SharedPreferencesUtils.setParam(context, Constants.CARDS, "");
            } else {
                SharedPreferencesUtils.setParam(context, Constants.CARDS, cardString.substring(cardNumber.length() + 1));
            }
        } else {
            SharedPreferencesUtils.setParam(context, Constants.CARDS, cardString.replace("," + cardNumber, ""));
            Log.e("wocao", "removeCards: " + SharedPreferencesUtils.getParam(context, Constants.CARDS, ""));
        }
    }

    public static void removeAll(Context context) {
        String cardString = (String) SharedPreferencesUtils.getParam(context, Constants.CARDS, "");
        SharedPreferencesUtils.setParam(context, Constants.CARDS, "");
    }
}
